package com.szgr.baoyin.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.StoreListAdapter;
import com.szgr.baoyin.model.Goods;
import com.szgr.baoyin.model.SearchItem;
import com.szgr.baoyin.myview.MyContainer;
import com.szgr.baoyin.myview.NoScrollListView;
import com.szgr.baoyin.myview.Tag;
import com.szgr.baoyin.myview.WheelView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.PopMenuDate;
import com.szgr.baoyin.utils.SystemBarTintManager;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActivity extends Activity implements View.OnClickListener, AbsListView.OnScrollListener, AdapterView.OnItemClickListener {

    private static final int HOT_SUCCESS = 3002;
    private LinearLayout menuView;
    private Dialog menuDialog;
    private WheelView wheelView;
    private MyContainer myContainer;
    private int index = 1;
    private List<String> data;
    private EditText et_search;
    private List<Goods> showData;
    private StoreListAdapter storeListAdapter;
    private int currentPage = 1;
    private LinearLayout ll_old;
    private ListView nslv_search;
    private SystemBarTintManager mTintManager;
    private DbUtils myDb;
    private List<SearchItem> searches;
    private TextView tv_noSearch;
    private MyContainer container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        initView();
        //判断操作系统的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 状态栏透明 需要在创建SystemBarTintManager之前调用。
            setTranslucentStatus(true);//方法如下
        }
        mTintManager = new SystemBarTintManager(this);
        // 设置状态栏背景
        mTintManager.setStatusBarTintEnabled(true);
        mTintManager.setStatusBarTintResource(R.color.main_blue);//颜色可以随便修改
    }

    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    private void initView() {
        showData = new ArrayList<>();
        myContainer = (MyContainer) findViewById(R.id.search_container);
//        myContainer.add(new Tag(1, "机床刀具"));
//        myContainer.add(new Tag(1, "机床配件"));
//        myContainer.add(new Tag(1, "配件"));
//        myContainer.add(new Tag(1, "保银品牌续保"));
//        myContainer.add(new Tag(1, "刀库"));
        myContainer.setOnTagSelectListener(new MyContainer.OnTagSelectListener() {
            @Override
            public void onTagSelected(Tag tag, int position) {
                getGoods(data.get(position),"","",false);
                et_search.setText(data.get(position));
            }
        });

        data = new ArrayList<>();

        initDialog("选择什么");
        findViewById(R.id.search_btn).setOnClickListener(this);
        et_search = (EditText) findViewById(R.id.search_edit);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s == null || s.length() == 0){
                    ll_old.setVisibility(View.VISIBLE);
                    nslv_search.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        Intent intent = getIntent();
        if(intent.hasExtra("search")){
            et_search.setText(intent.getStringExtra("search"));
        }

        ll_old = (LinearLayout) findViewById(R.id.search_old);
        nslv_search = (ListView) findViewById(R.id.search_list_view);
        storeListAdapter = new StoreListAdapter(this, showData);
        nslv_search.setAdapter(storeListAdapter);
        nslv_search.setOnItemClickListener(this);
        nslv_search.setOnScrollListener(this);

        getSearchKeyWord();

        tv_noSearch = (TextView) findViewById(R.id.no_search);
        container = (MyContainer) findViewById(R.id.search_container_top);
        container.setOnTagSelectListener(new MyContainer.OnTagSelectListener() {
            @Override
            public void onTagSelected(Tag tag, int position) {
                getGoods(searches.get(position).getName(), "", "", false);
                et_search.setText(searches.get(position).getName());
            }
        });
        myDb = DbUtils.create(this);
        drawTag();
    }

    private void drawTag() {
        try {
            searches = myDb.findAll(SearchItem.class);
            if(searches != null){
                tv_noSearch.setVisibility(View.GONE);
                container.setVisibility(View.VISIBLE);

                for (SearchItem str : searches) {
                    container.add(new Tag(1, str.getName()));
                }
                container.drawTags();
            }else{
                tv_noSearch.setVisibility(View.VISIBLE);
                container.setVisibility(View.GONE);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    private void getSearchKeyWord() {
        StringRequest sr = new StringRequest(Request.Method.GET, Constant.URL_HOT_SEARCH,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if(jsonObject.has("datas")){
                                JSONArray datas = jsonObject.getJSONArray("datas");
                                JSONArray array = (JSONArray) datas.get(0);
                                for (int i = 0; i < array.length(); i++) {
                                    String string = array.getString(i);
                                    data.add(string);
                                }
                                mHandler.obtainMessage(HOT_SUCCESS).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.REQUEST_SUCCESS:
                    ll_old.setVisibility(View.GONE);
                    nslv_search.setVisibility(View.VISIBLE);
                    break;
                case HOT_SUCCESS:
                    for (String str : data) {
                        myContainer.add(new Tag(1,str));
                    }
                    myContainer.drawTags();
                    break;
            }
        }
    };

    /**
     * 获取商品
     */
    private void getGoods(final String goods_name, final String key, final String order,final boolean isSearchChange) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_GET_GOODS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("----->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code) && jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                JSONArray goods_list = datas.getJSONArray("goods_list");
                                Gson gson = new Gson();
                                List<Goods> data = (List<Goods>)gson.fromJson(goods_list.toString(), new TypeToken<List<Goods>>() {
                                }.getType());
                                if(data.size() == 0){
                                    ToastUtils.showToast("没有更多商品了");
                                }
                                mHandler.obtainMessage(Constant.REQUEST_SUCCESS).sendToTarget();
                                if(isSearchChange) {
                                    showData.clear();
                                }
                                showData.addAll(data);
                                storeListAdapter.setData(showData);
                                currentPage ++ ;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
//                map.put("store_id","");
                map.put("goods_name",goods_name);
//                map.put("gc_id",gc_id);
//                map.put("gc_deep","1");
//                map.put("min_price",minPrice + "");
//                map.put("max_price",maxPrice + "");
//                map.put("goods_state","1");
                map.put("key",key);
                map.put("order",order);
                map.put("page",currentPage + "");
                map.put("pagesize",Constant.PAGE_SIZE + "");
//                map.put("imgsize",Constant.IMG_SIZE + "");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_btn:
//                wheelView.setSeletion(0);
//                wheelView.setItems(data);
//                menuDialog.show();

//                PopMenuDate popMenuDate2 = new PopMenuDate(this,true);
//                popMenuDate2.setTitle("选择日期");
//                // popMenuDate.setDate("2015-02-28");//默认为今天
//                popMenuDate2.setTextViewOfShow(et_search);
//                popMenuDate2.show(et_search, 0, getWindowManager()
//                        .getDefaultDisplay().getHeight());
                if(!MyTool.isEmpty(et_search)) {
                    String text = MyTool.getText(et_search);
                    try {
                        SearchItem si = new SearchItem();
                        si.setName(text);
                        myDb.saveBindingId(si);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    getGoods(text, "", "", true);
                    currentPage = 1;
                }else{
                    ToastUtils.showToast("请输入关键字搜索");
                }
                break;
        }
    }

    public void initDialog(String title){
        menuView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_wheel_view,null);
        View confirm = menuView.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = data.get(index - 1);
                myContainer.add(new Tag(1, str));
                myContainer.drawTags();

                menuDialog.dismiss();
                index = 1;
            }
        });
        View cancel = menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuDialog.dismiss();
                index = 1;
            }
        });
        TextView tv_title = (TextView) menuView.findViewById(R.id.title);
        tv_title.setText(title);
        wheelView = (WheelView) menuView.findViewById(R.id.wheel_view);

        wheelView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                index = selectedIndex;
            }
        });
        menuDialog = MyTool.getMenuDialog(this, menuView);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(scrollState == SCROLL_STATE_IDLE){
            if(nslv_search.getLastVisiblePosition() == nslv_search.getCount() - 1){
                getGoods(MyTool.getText(et_search),"1","1",false);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Goods goods = showData.get(position);
        String goods_stcids = goods.getGoods_stcids();
        if(!",13,".equals(goods_stcids)) {
            Intent storeIntent = new Intent(this, StoreDeatilActivity.class);
            storeIntent.putExtra("goods_id", goods.getGoods_id());
            if(",9,".equals(goods_stcids)) {
                storeIntent.putExtra("type", Constant.TYPE_01);
            }else if(",12,".equals(goods_stcids)){
                storeIntent.putExtra("type", Constant.TYPE_03);
            }
            startActivity(storeIntent);
        }
    }
}
